package com.book.bookmanager.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.system.UserInfo;
import com.book.bookmanager.pojo.Book;
import com.book.bookmanager.pojo.Head;
import com.book.bookmanager.pojo.Person;
import com.book.bookmanager.service.bookService;
import com.book.bookmanager.service.personService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("book")
public class bookController {
	@Autowired
	private bookService bs;
	@Autowired
	private personService ps;

	/**
	 * 全查
	 */
	@GetMapping("queryAll")
	public String queryAll(Model model) {
		List<Book> list = bs.queryAll();
		/**
		 * 存入model
		 */
		model.addAttribute("list", list);
		return "showAll";
	}

	@RequestMapping("removeById")
	public String removeById(Integer id) {
		try {
			bs.removeById(id);
			return "redirect:/book/queryAll";
		} catch (Exception e) {
			return "error";
		}
	}

	@GetMapping("toAdd")
	public String toAdd() {

		return "addBook";
	}

	@RequestMapping("addBook")
	public String addBook(Book book) {
		try {
			bs.addBook(book);
			return "redirect:/book/queryAll";
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	}


	@RequestMapping("upload")
	public String addBook(Book book,
						  /**
						   *定义一个 MultipartFile 类型的参数 file
						   * */
						  @RequestParam("file") MultipartFile file,
						  Model model) {
		//非空校验
		if ((file.getOriginalFilename().isEmpty())) {
			model.addAttribute("error", "error");
			return "redirect:/book/queryAll";
		}
		/***
		 * 要上传的文件名
		 */

		String originalFileName = file.getOriginalFilename();
		/***
		 * 获取文件后缀
		 */
		String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
		String fileTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		/**
		 *生成图片名称，使用 UUID 避免相同图片名冲突，加上图片后缀
		 */
		String photoName = fileTime + suffix;

		/**
		 * 图片保存路径(绝对路径/相对路径)
		 *这里为什么还要用相对路径，只用绝对路径不行么?
		 * 因为禁止浏览器访问本地磁盘绝对路径路径，因此最简单的办法就是配置一个绝对路径用来保存文件，一个相对路径提供给浏览器访问
		 **/
		String photoPathAbsolute = "C:/Users/lsx/IdeaProjects/bookmanager/src/main/webapp/uploaded" + photoName; //绝对路径
		String photoPathRelative = "uploaded/" + photoName; //相对路径
		//生成文件(绝对路径)
		File saveFile = new File(photoPathAbsolute);
		if (saveFile.exists()) {
			System.out.println("已存在");
		}
		try {
			file.transferTo(saveFile);
			book.setSfile(photoPathRelative);
			bs.addPhoto(book);
			bs.addBook(book);
			return "redirect:/book/queryAll";
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	}


	@GetMapping("queryById")
	public String queryById(Integer id, Model model) {
		Book book = bs.queryById(id);
		model.addAttribute("book", book);
		return "update";
	}

	@RequestMapping("changeBook")
	public String changeBook(Book book) {
		try {
			bs.changeBook(book);
			return "redirect:/book/queryAll";
		} catch (Exception e) {
			return "error";
		}
	}

	@RequestMapping("buySuccess")
	public String buySuccess(HttpSession session, Model model, Integer id, Map<String, Object> map, HttpServletResponse response) {
		/**
		 * 接收用户余额信息
		 */
		try {
			String user1 = (String) session.getAttribute("user");
			System.out.println(user1);
			Person person = ps.queryByName(user1);
			Double balance = person.getBalance();
			/**
			 * 接收图书信息
			 */
			Book book = bs.queryById(id);
			Double price = book.getPrice();
			Double balance1 = balance - price;
			if (balance1 < 0.00) {
				model.addAttribute("余额不足，请充值");
				response.getWriter().write("<script>alert('余额不足，购买失败!');</script>");
				return "redirect:/book/toRecharge";
			} else {
				person.setBalance(balance1);
				ps.changePerson(person);
				model.addAttribute("购买成功");
				return "redirect:/book/queryAll";
			}
		} catch (Exception e) {
			return "error";
		}
	}

	@RequestMapping("toRecharge")
	public String toRecharge() {
		return "Recharge";
	}
}
